﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CourseScheduling.DataAccess;

namespace CourseScheduling
{
    public partial class StudentRequestForm : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                initNew();
                LoadCurrentState();
            }

            AddRequestRows();
        }

        private void initNew()
        {
            CSDataManager mgr = Application["CSDataManager"] as CSDataManager;
            
            // Init year
            //
            int nCurYear = DateTime.Now.Year;
            for (int i = 0; i < 4; ++i)
            {
                var item = new ListItem(nCurYear.ToString(), nCurYear.ToString());
                ddlYear.Items.Add(item);
                ++nCurYear;
             }

            // Init courses
            //
            var courses = mgr.getCourses();
            foreach (var course in courses)
            {
                var item = new ListItem(course.Code + " - " + course.Description, 
                                        course.Code);
                ddlCourses.Items.Add(item);
            }

            // Init days of week
            //
            var days = mgr.getDayOFWeek();
            foreach (var day in days)
            {
                var item = new ListItem(day.Description, day.Id.ToString());
                ddlDay.Items.Add(item);
            }
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            var reqs = Session["StudentRequests"] as List<CSCourseRequest>;
            if (reqs == null)
            {
                // This should never happen but it is better to be safe
                // than sorry.
                //
                Session["StudentRequests"] = new List<CSCourseRequest>();
            }

            var req = new CSCourseRequest();
            SetStudentRequest(req);
            req.IsRequired = Req.Checked;
            req.CourseCode = ddlCourses.SelectedValue;

            bool bFound = false;
            foreach (var req2 in reqs)
            {
                if (string.Compare(req2.CourseCode, ddlCourses.SelectedValue, true) == 0)
                {
                    bFound = true;
                    break;
                }
            }

            if (!bFound)
            {
                reqs.Add(req);

                SaveCurrentState();
                Response.Redirect(Request.Path);
            }
        }

        protected void LoadCurrentState()
        {
            string str = Session["tbStudentNo"] as string;
            if (!string.IsNullOrEmpty(str))
            {
                tbStudentNo.Text = str;
            }

            str = Session["tbStudentName"] as string;
            if (!string.IsNullOrEmpty(str))
            {
                tbStudentName.Text = str;
            }

            str = Session["ddlSemester"] as string;
            if (!string.IsNullOrEmpty(str))
            {
                ddlSemester.SelectedValue = str;
            }

            str = Session["ddlYear"] as string;
            if (!string.IsNullOrEmpty(str))
            {
                ddlYear.SelectedValue = str;
            }

            str = Session["ddlCourses"] as string;
            if (!string.IsNullOrEmpty(str))
            {
                ddlCourses.SelectedValue = str;
            }

            str = Session["ddlDay"] as string;
            if (!string.IsNullOrEmpty(str))
            {
                ddlDay.SelectedValue = str;
            }

            str = Session["ddlTime"] as string;
            if (!string.IsNullOrEmpty(str))
            {
                ddlTime.SelectedValue = str;
            }

            str = Session["ProgramCodeList"] as string;
            if (!string.IsNullOrEmpty(str))
            {
                ProgramCodeList.SelectedValue = str;
            }

            str = Session["IsRequired"] as string;
            if (!string.IsNullOrEmpty(str))
            {
                Req.Checked = Boolean.Parse(str);
            }
        }

        protected void SaveCurrentState()
        {
            Session["tbStudentNo"] = tbStudentNo.Text;
            Session["tbStudentName"] = tbStudentName.Text;
            Session["ddlSemester"] = ddlSemester.SelectedValue;
            Session["ddlYear"] = ddlYear.SelectedValue;
            Session["ddlCourses"] = ddlCourses.SelectedValue;
            Session["ddlDay"] = ddlDay.SelectedValue;
            Session["ddlTime"] = ddlTime.SelectedValue;
            Session["ProgramCodeList"] = ProgramCodeList.SelectedValue;
            Session["IsRequired"] = Req.Checked;
        }

        protected void SetStudentRequest(CSCourseRequest req)
        {
            req.Date = DateTime.Now;

            int day = -1;
            int.TryParse(ddlDay.SelectedValue, out day);
            req.DayOfWeek = day;
            
            req.Name = tbStudentName.Text;
            req.NNumber = tbStudentNo.Text;
            req.ProgramCode = ProgramCodeList.SelectedValue;
            req.Semester = ddlSemester.SelectedValue;
            req.TimeOfDay = ddlTime.SelectedValue;
            int year = -1;
            int.TryParse(ddlYear.SelectedValue, out year);
            req.Year = year;
        }

        protected void AddRequestRows()
        {
            var reqs = Session["StudentRequests"] as List<CSCourseRequest>;

            // Get the data manager from the application
            //
            var mgr = Application["CSDataManager"] as CSDataManager;

            int rowId = 0;
            foreach (var req in reqs)
            {
                var row = new TableRow();

                // Course number
                //
                var cell = new TableCell();
                cell.Text = req.CourseCode;
                row.Cells.Add(cell);

                // Course name
                //
                var course = mgr.getCourse(req.CourseCode);

                cell = new TableCell();
                if (course != null)
                {
                    cell.Text = course.Description;
                }
                row.Cells.Add(cell);

                // Day of week
                //
                var dow = mgr.getDOW(req.DayOfWeek.ToString());

                cell = new TableCell();
                if (dow != null)
                {
                    cell.Text = dow.Description;
                }
                row.Cells.Add(cell);

                // Time of day
                //
                cell = new TableCell();
                cell.Text = req.TimeOfDay;
                row.Cells.Add(cell);

                //Is the course required, or an elective
                //
                cell = new TableCell();
                if (req.IsRequired)
                {
                    cell.Text = "true";
                }
                else
                {
                    cell.Text = "false";
                }
                row.Cells.Add(cell);

                // Command
                //
                cell = new TableCell();
                cell.HorizontalAlign = HorizontalAlign.Center;

                var button = new Button();
                button.CommandArgument = req.CourseCode;
                //button.ID = "btnDel" + rowId.ToString();
                button.Click += Delete_OnClick;
                button.Text = "Delete";

                cell.Controls.Add(button);
                row.Cells.Add(cell);

                tblCourses.Rows.Add(row);
                ++rowId;
            }
        }

        protected void Delete_OnClick(object sender, EventArgs e)
        {
            var reqs = Session["StudentRequests"] as List<CSCourseRequest>;
            var button = sender as Button;
            var strCourseCode = button.CommandArgument;

            var removeReqs = new List<CSCourseRequest>();
            foreach (var req in reqs)
            {
                if (string.Compare(req.CourseCode, strCourseCode, true) == 0)
                {
                    removeReqs.Add(req);
                }
            }

            foreach (var req in removeReqs)
            {
                reqs.Remove(req);
            }

            Response.Redirect(Request.Path);
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            var reqs = Session["StudentRequests"] as List<CSCourseRequest>;
            var mgr = Application["CSDataManager"] as CSDataManager;
            foreach (var req in reqs)
            {
                // Update the request with latest form data
                //
                SetStudentRequest(req);
                mgr.createStudentRequest(req);
            }
            Response.Redirect("CourseRequestConfirmation.aspx");
        }
    }
}